package edu.hrbu.kwaidu.util;

import cn.hutool.core.codec.Base64;
import cn.hutool.crypto.digest.MD5;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

import static edu.hrbu.kwaidu.constant.SystemConstant.SYSTEM_ENCRYPT_SALT;


/**
 * @author xudengyu
 */
public class CustomUtil {
    /*获取异常代码所在行数*/
    public static int getLineNumber(Exception e) {
        StackTraceElement[] trace = e.getStackTrace();
        if (trace == null || trace.length == 0) return -1; //
        return trace[0].getLineNumber();
    }

    /*密码加盐加密*/
    public static String getMd5Pwd(String originalPwd) {
        // md5是单向hash函数，无法进行解密
        return new MD5(SYSTEM_ENCRYPT_SALT.getBytes()).digestHex16(originalPwd);
    }

    /*获取加密token >> phone base64编码*/
    public static String getEncodeToken(String phone) {
        return Base64.encode(phone);
    }

    /*获取解析token*/
    public static String getDecodeToken(String token) {
        return Base64.decodeStr(token);
    }

    /*获取request*/
    public static HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
    }
}
